package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        if (userId != null) {
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId).and("type").is(1)), ApBehaviorEntry.class);
            if (behaviorEntry == null) {
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType((short) 1);
                behaviorEntry.setRefId(userId);
                behaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        if (equipmentId != null) {
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId).and("type").is(1)), ApBehaviorEntry.class);
            if (behaviorEntry == null) {
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType((short) 0);
                behaviorEntry.setRefId(equipmentId);
                behaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        return null;
    }
}
